package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.advice.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.mapper.RoomInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private LeaseAgreementService leaseAgreementService;

    public void deleteSonTTable(Long id, ItemType type) {
        // 删除现有的房间图片信息
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, type);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        // 删除现有的房间租赁条款信息
        LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        roomLeaseTermLambdaQueryWrapper.eq(RoomLeaseTerm::getRoomId, id);
        roomLeaseTermService.remove(roomLeaseTermLambdaQueryWrapper);

        // 删除现有的房间支付方式信息
        LambdaQueryWrapper<RoomPaymentType> roomPaymentTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomPaymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId, id);
        roomPaymentTypeService.remove(roomPaymentTypeLambdaQueryWrapper);

        // 删除现有的房间属性值信息
        LambdaQueryWrapper<RoomAttrValue> roomAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomAttrValueLambdaQueryWrapper.eq(RoomAttrValue::getRoomId, id);
        roomAttrValueService.remove(roomAttrValueLambdaQueryWrapper);

        // 删除现有的房间设施信息
        LambdaQueryWrapper<RoomFacility> roomFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomFacilityLambdaQueryWrapper.eq(RoomFacility::getRoomId, id);
        roomFacilityService.remove(roomFacilityLambdaQueryWrapper);

        // 删除现有的房间标签信息
        LambdaQueryWrapper<RoomLabel> roomLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomLabelLambdaQueryWrapper.eq(RoomLabel::getRoomId, id);
        roomLabelService.remove(roomLabelLambdaQueryWrapper);
    }


    public void customPage(Page<RoomItemVo> page, RoomQueryVo queryVo) {
        roomInfoMapper.customSelectPage(page, queryVo);
    }

    /**
     * 自定义保存或更新房间信息方法
     * 该方法首先判断是保存还是更新操作，然后处理房间相关的图片、租赁条款、支付方式、属性值、设施和标签信息
     *
     * @param roomSubmitVo 房间提交视图对象，包含房间信息及其关联的图片、租赁条款等信息
     */
    @Override
    public void customSaveOrUpdate(RoomSubmitVo roomSubmitVo) {
        // 判断房间信息是否已存在
        boolean exits = roomSubmitVo.getId() != null;
        // 保存或更新房间基本信息
        saveOrUpdate(roomSubmitVo);
        // 如果房间信息已存在，则删除现有的图片、租赁条款等信息，以支持更新操作
        if (exits) {
            deleteSonTTable(roomSubmitVo.getId(), ItemType.ROOM);
        }
        // 处理房间图片信息
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(roomSubmitVo.getId());
                graphInfo.setItemType(ItemType.ROOM);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

        // 处理房间租赁条款信息
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)) {
            List<RoomLeaseTerm> leaseTermList = new ArrayList<>(leaseTermIds.size());
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder().leaseTermId(leaseTermId)
                        .roomId(roomSubmitVo.getId()).build();
                leaseTermList.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(leaseTermList);
        }

        // 处理房间支付方式信息
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)) {
            List<RoomPaymentType> roomPaymentTypeList = new ArrayList<>(paymentTypeIds.size());
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder().paymentTypeId(paymentTypeId)
                        .roomId(roomSubmitVo.getId()).build();
                roomPaymentTypeList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }

        // 处理房间属性值信息
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)) {
            List<RoomAttrValue> roomAttrValues = new ArrayList<>(attrValueIds.size());
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue build = RoomAttrValue.builder().attrValueId(attrValueId)
                        .roomId(roomSubmitVo.getId()).build();
                roomAttrValues.add(build);
            }
            roomAttrValueService.saveBatch(roomAttrValues);
        }

        // 处理房间设施信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<RoomFacility> roomFacilities = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = RoomFacility.builder().facilityId(facilityInfoId)
                        .roomId(roomSubmitVo.getId()).build();
                roomFacilities.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilities);
        }

        // 处理房间标签信息
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIds)) {
            List<RoomLabel> roomLabelList = new ArrayList<>(labelInfoIds.size());
            for (Long labelInfoId : labelInfoIds) {
                RoomLabel roomLabel = RoomLabel.builder().labelId(labelInfoId)
                        .roomId(roomSubmitVo.getId()).build();
                roomLabelList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelList);
        }
    }

    /**
 * 根据ID自定义删除记录
 * 在删除之前，会检查与给定房间ID相关的租赁协议是否存在
 * 如果存在租赁协议，则抛出删除错误异常，防止数据一致性问题
 *
 * @param id 房间ID，用于标识要删除的记录
 */
@Override
public void customRemoveById(Long id) {
    // 创建查询包装器，用于条件查询
    LambdaQueryWrapper<LeaseAgreement> wrapper = new LambdaQueryWrapper<>();
    // 设置查询条件：根据房间ID等于给定的ID
    wrapper.eq(LeaseAgreement::getRoomId, id);
    wrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWING,LeaseStatus.RENEWING);
    // 计算满足条件的租赁协议数量
    long count = leaseAgreementService.count(wrapper);
    // 如果存在相关的租赁协议，则抛出删除错误异常
    if (count > 0){
        throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
    }
    // 删除子表中的相关记录
    deleteSonTTable(id, ItemType.ROOM);
    // 调用方法删除当前表中的记录
    removeById(id);
}

    @Override
    public RoomDetailVo customGetById(Long id) {
        return roomInfoMapper.customSelectById(id);
    }
}




